package com.linxi.rpccompensation.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.xml.crypto.dsig.keyinfo.KeyValue;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * fastjson 工具类
 *
 * @author admin
 */
public class JsonUtils {
	private static final SerializeConfig config = new SerializeConfig();
	private static final SerializerFeature[] features;

	static {
		config.put(Date.class, new JSONLibDataFormatSerializer());
		config.put(java.sql.Date.class, new JSONLibDataFormatSerializer());
		features = new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullStringAsEmpty};
	}

	public JsonUtils() {
	}

	public static String toJSONString(Object object) {
		return JSON.toJSONString(object, config, features);
	}

	public static String toJSONNoFeatures(Object object) {
		return JSON.toJSONString(object, config, new SerializerFeature[0]);
	}

	public static Object toBean(String text) {
		return JSON.parse(text);
	}

	public static <T> T toBean(String text, Class<T> clazz) {
		return JSON.parseObject(text, clazz);
	}

	public static <T> Object[] toArray(String text) {
		return toArray(text, (Class) null);
	}

	public static <T> Object[] toArray(String text, Class<T> clazz) {
		return JSON.parseArray(text, clazz).toArray();
	}

	public static <T> List<T> toList(String text, Class<T> clazz) {
		return JSON.parseArray(text, clazz);
	}

	public static Object bean2Json(KeyValue keyvalue) {
		String textJson = JSON.toJSONString(keyvalue);
		return JSON.parse(textJson);
	}

	public static Object text2Json(String text) {
		return JSON.parse(text);
	}

	public static Map string2Collect(String s) {
		return JSONObject.parseObject(s);
	}

	public static String collect2String(Map m) {
		return JSONObject.toJSONString(m);
	}
}
